<?php

    /**
     * Tecdoc
     *
     * @package      Core
     * @subpackage   Soap
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
	class Core_Soap_Chronopost extends Core_Soap_Abstract
	{

    ////////////////////////////////////////////////////////////////////////////
	//                                Constants                               //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Expedition
         */
      	const URL_SERVICE_EXPEDITION    = 'http://wsshipping.chronopost.fr/shipping/services/services/ServiceEProcurement';
    	const URL_WSDL_EXPEDITION       = 'http://wsshipping.chronopost.fr/shipping/services/services/ServiceEProcurement?wsdl';

        /**
         * Suivi
         */
    	const URL_SERVICE_SUIVI         = 'http://ws.chronopost.fr/axis/services/ServiceEProcurement';
    	const URL_WSDL_SUIVI            = 'http://ws.chronopost.fr/axis/services/ServiceEProcurement?wsdl';

        /**
         * Recherche BT
         */
    	const URL_SERVICE_RECHERCHEBT   = 'http://wsshipping.chronopost.fr/soap.point.relais/services/ServiceRechercheBt';
    	const URL_WSDL_RECHERCHEBT      = 'http://wsshipping.chronopost.fr/soap.point.relais/services/ServiceRechercheBt?wsdl';

        /**
         * Products
         */
        const PRODUIT_CHRONO_13H        = '01';
        const PRODUIT_CHRONO_10H        = '02';
        const PRODUIT_CHRONO_18H        = '16';
        const PRODUIT_CHRONO_EXPRESS    = '17';
        const PRODUIT_CHRONO_PREMIUM    = '37';
        const PRODUIT_CHRONO_CLASSIC    = '44';
        const PRODUIT_CHRONO_RELAIS     = '86';

        /**
         * Services
         */
        const SERVICE_LIVRAISON_DEFAULT     = '0';
        const SERVICE_LIVRAISON_LUNDI       = '1';
        const SERVICE_LIVRAISON_MARDI       = '2';
        const SERVICE_LIVRAISON_MERCREDI    = '3';
        const SERVICE_LIVRAISON_JEUDI       = '4';
        const SERVICE_LIVRAISON_VENDREDI    = '5';
        const SERVICE_LIVRAISON_SAMEDI      = '6';

        /**
         * Extensions
         */
        const EXTENSION_GENERATION_FICHE_SUIVI_PDF  = 'PDF';
        const EXTENSION_GENERATION_FICHE_SUIVI_PS   = 'PS';

	////////////////////////////////////////////////////////////////////////////
	//                                 Methods                                //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Calls the SOAP server with the requested parameters
         *
         * @param       string      $method
         * @param       array       $params
         * @throws      Core_Exception
         * @return      array
         */
        public function call($method, array $params = array())
        {
            if (!($this->_adapter) instanceof Core_Soap_Adapter_Abstract) {
                throw new Core_Exception('Fatal error: adapter inst\'t an instance of Core_Soap_Adapter_Abstract');
            }

            $this->_adapter->setWsdl($this->_url);

            if ($method === 'ExpeditionV2') {
                return $this->_expeditionV2($params);
            }

            $result = $this->_adapter->call($method, $params);

            if (isset($result['status']) && $result['status'] != '200') {
                throw new Core_Exception($result['statusText']);
            }

            if (isset($result['data']['array'])) {
                return $result['data']['array'];
            } else {
                return array();
            }
        }

        /**
         * Exceptional process for ExpeditionV2 method
         *
         * @param       array       $params
         * @return      array
         */
        private function _expeditionV2(array $params = array())
        {
            $msg = sprintf('<?xml version="1.0" encoding="UTF-8"?>
                            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                            <soapenv:Body>
                              <ns1:expeditionV2 soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:server.eprocurement.soap.chronopost.fr">
                               <esdParams xsi:type="ns2:ESDParams" xsi:nil="true" xmlns:ns2="http://esd.interfaces.eprocurement.soap.chronopost.fr"/>
                               <header href="#id0"/>
                               <shipper href="#id1"/>
                               <customer href="#id2"/>
                               <recipient href="#id3"/>
                               <ref href="#id4"/>
                               <skybill href="#id5"/>
                               <skybillParams href="#id6"/>
                               <password xsi:type="xsd:string"><![CDATA[%s]]></password>
                              </ns1:expeditionV2>
                              <multiRef id="id4" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns3:Ref" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns3="http://declaration.interfaces.eprocurement.soap.chronopost.fr">
                               <customerSkybillNumber xsi:type="xsd:string">01</customerSkybillNumber>
                               <recipientRef xsi:type="xsd:string"><![CDATA[%s]]></recipientRef>
                               <shipperRef xsi:type="xsd:string"><![CDATA[%s]]></shipperRef>
                              </multiRef>
                              <multiRef id="id1" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns4:Shipper" xmlns:ns4="http://declaration.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                               <shipperAdress1 xsi:type="xsd:string"><![CDATA[%s]]></shipperAdress1>
                               <shipperAdress2 xsi:type="xsd:string"><![CDATA[%s]]></shipperAdress2>
                               <shipperCity xsi:type="xsd:string"><![CDATA[%s]]></shipperCity>
                               <shipperCivility xsi:type="xsd:string"><![CDATA[%s]]></shipperCivility>
                               <shipperContactName xsi:type="xsd:string"><![CDATA[%s]]></shipperContactName>
                               <shipperCountry xsi:type="xsd:string"><![CDATA[%s]]></shipperCountry>
                               <shipperEmail xsi:type="xsd:string"><![CDATA[%s]]></shipperEmail>
                               <shipperMobilePhone xsi:type="xsd:string"></shipperMobilePhone>
                               <shipperName xsi:type="xsd:string"><![CDATA[%s]]></shipperName>
                               <shipperName2 xsi:type="xsd:string"></shipperName2>
                               <shipperPhone xsi:type="xsd:string"><![CDATA[%s]]></shipperPhone>
                               <shipperPreAlert xsi:type="xsd:int">2</shipperPreAlert>
                               <shipperZipCode xsi:type="xsd:string"><![CDATA[%s]]></shipperZipCode>
                              </multiRef>
                              <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns5:Header" xmlns:ns5="http://declaration.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                               <accountNumber xsi:type="xsd:int"><![CDATA[%s]]></accountNumber>
                               <idEmit xsi:type="xsd:string">CHRFR</idEmit>
                               <subAccount xsi:type="xsd:int">0</subAccount>
                              </multiRef>
                              <multiRef id="id3" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns6:Recipient" xmlns:ns6="http://declaration.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                               <recipientAdress1 xsi:type="xsd:string"><![CDATA[%s]]></recipientAdress1>
                               <recipientAdress2 xsi:type="xsd:string"><![CDATA[%s]]></recipientAdress2>
                               <recipientCity xsi:type="xsd:string"><![CDATA[%s]]></recipientCity>
                               <recipientContactName xsi:type="xsd:string"><![CDATA[%s]]></recipientContactName>
                               <recipientCountry xsi:type="xsd:string"><![CDATA[%s]]></recipientCountry>
                               <recipientEmail xsi:type="xsd:string"><![CDATA[%s]]></recipientEmail>
                               <recipientMobilePhone xsi:type="xsd:string"></recipientMobilePhone>
                               <recipientName xsi:type="xsd:string"><![CDATA[%s]]></recipientName>
                               <recipientName2 xsi:type="xsd:string"/>
                               <recipientPhone xsi:type="xsd:string"><![CDATA[%s]]></recipientPhone>
                               <recipientPreAlert xsi:type="xsd:int">1</recipientPreAlert>
                               <recipientZipCode xsi:type="xsd:string"><![CDATA[%s]]></recipientZipCode>
                              </multiRef>
                                <multiRef id="id5" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns7:Skybill" xmlns:ns7="http://declaration.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                                   <codCurrency xsi:type="xsd:string">EUR</codCurrency>
                                   <codValue xsi:type="soapenc:float">0.0</codValue>
                                   <content1 xsi:type="xsd:string"></content1>
                                   <content2 xsi:type="xsd:string"></content2>
                                   <content3 xsi:type="xsd:string"></content3>
                                   <content4 xsi:type="xsd:string"></content4>
                                   <content5 xsi:type="xsd:string"></content5>
                                   <customsCurrency xsi:type="xsd:string">EUR</customsCurrency>
                                   <customsValue xsi:type="soapenc:float">0.0</customsValue>
                                   <evtCode xsi:type="xsd:string">DC</evtCode>
                                   <insuredCurrency xsi:type="xsd:string">EUR</insuredCurrency>
                                   <insuredValue xsi:type="soapenc:float">0.0</insuredValue>
                                   <objectType xsi:type="xsd:string">MAR</objectType>
                                   <productCode xsi:type="xsd:string"><![CDATA[%s]]></productCode>
                                   <service xsi:type="xsd:string"><![CDATA[%s]]></service>
                                   <shipDate xsi:type="xsd:dateTime"><![CDATA[%s]]></shipDate>
                                   <shipHour xsi:type="xsd:int"><![CDATA[%s]]></shipHour>
                                   <weight xsi:type="soapenc:float"><![CDATA[%s]]></weight>
                                   <weightUnit xsi:type="xsd:string"><![CDATA[%s]]></weightUnit>
                                </multiRef>
                              <multiRef id="id2" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns8:Customer" xmlns:ns8="http://declaration.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                               <customerAdress1 xsi:type="xsd:string"><![CDATA[%s]]></customerAdress1>
                               <customerAdress2 xsi:type="xsd:string"><![CDATA[%s]]></customerAdress2>
                               <customerCity xsi:type="xsd:string"><![CDATA[%s]]></customerCity>
                               <customerCivility xsi:type="xsd:string"><![CDATA[%s]]></customerCivility>
                               <customerContactName xsi:type="xsd:string"><![CDATA[%s]]></customerContactName>
                               <customerCountry xsi:type="xsd:string"><![CDATA[%s]]></customerCountry>
                               <customerEmail xsi:type="xsd:string"><![CDATA[%s]]></customerEmail>
                               <customerMobilePhone xsi:type="xsd:string"></customerMobilePhone>
                               <customerName xsi:type="xsd:string"><![CDATA[%s]]></customerName>
                               <customerName2 xsi:type="xsd:string"></customerName2>
                               <customerPhone xsi:type="xsd:string"><![CDATA[%s]]></customerPhone>
                               <customerPreAlert xsi:type="xsd:int">1</customerPreAlert>
                               <customerZipCode xsi:type="xsd:string"><![CDATA[%s]]></customerZipCode>
                              </multiRef>
                              <multiRef id="id6" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns9:SkybillParams" xmlns:ns9="http://skybill.interfaces.eprocurement.soap.chronopost.fr" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                               <mode xsi:type="xsd:string"><![CDATA[%s]]></mode>
                              </multiRef>
                             </soapenv:Body>
                            </soapenv:Envelope>',

                                $params['Password']['password'],

                                $params['Ref']['recipientRef'],
                                $params['Ref']['shipperRef'],

                                $params['Shipper']['shipperAdress1'],
                                $params['Shipper']['shipperAdress2'],
                                $params['Shipper']['shipperCity'],
                                $params['Shipper']['shipperCivility'],
                                $params['Shipper']['shipperContactName'],
                                $params['Shipper']['shipperCountry'],
                                $params['Shipper']['shipperEmail'],
                                $params['Shipper']['shipperName'],
                                $params['Shipper']['shipperPhone'],
                                $params['Shipper']['shipperZipCode'],

                                $params['Header']['accountNumber'],

                                $params['Recipient']['recipientAdress1'],
                                $params['Recipient']['recipientAdress2'],
                                $params['Recipient']['recipientCity'],
                                $params['Recipient']['recipientContactName'],
                                $params['Recipient']['recipientCountry'],
                                $params['Recipient']['recipientEmail'],
                                $params['Recipient']['recipientName'],
                                $params['Recipient']['recipientPhone'],
                                $params['Recipient']['recipientZipCode'],

                                $params['Skybill']['productCode'],
                                $params['Skybill']['service'],
                                $params['Skybill']['shipDate'],
                                $params['Skybill']['shipHour'],
                                $params['Skybill']['weight'],
                                $params['Skybill']['weightUnit'],

                                $params['Customer']['customerAdress1'],
                                $params['Customer']['customerAdress2'],
                                $params['Customer']['customerCity'],
                                $params['Customer']['customerCivility'],
                                $params['Customer']['customerContactName'],
                                $params['Customer']['customerCountry'],
                                $params['Customer']['customerEmail'],
                                $params['Customer']['customerName'],
                                $params['Customer']['customerPhone'],
                                $params['Customer']['customerZipCode'],

                                $params['SkybillParams']['mode']);

            $client = new nusoap_client($this->_url, true);
            $client->soap_defencoding   = 'UTF-8';
            $client->decode_utf8        = false;

            $result = $client->send(self::_escape($msg), '');

            return $result['expeditionV2Return'];
        }

        /**
         * Escapes string for Chronopost messages
         *
         * @staticvar   array       $url_escape_to
         * @staticvar   array       $url_escape_from
         * @param       string      $str
         * @return      string
         */
        private static function _escape($str)
        {
            static $url_escape_to = null;
            static $url_escape_from = null;

            if ($url_escape_from == null) {
                $url_escape_to = explode(' ', 'a a a e e e e i i o o u u u A A A E E E E I I O O U U U c c');
                $url_escape_from = explode(' ', 'à â ä é è ê ë ï î ô ö ù ü û À Â Ä É È Ê Ë Ï Î Ô Ö Ù Ü Û ç Ç');
            }

            $str = str_replace($url_escape_from, $url_escape_to, $str);

            return $str;
        }
	}